<template>
  <div class="produceFactoryDialog">
    <div class="panelWrap">
      <div class="title flex flexac flexjcsb fs14 cfff fwb pl p-r-20">
        <div>{{ fileType ? '电梯档案Excel导入' : '维保人员Excel导入' }}</div>
        <i class="el-icon-close" @click="handleCloseDialog" />
      </div>
      <div class="con">
        <el-upload
          ref="upload"
          class="upload-demo"
          :limit="limitNum"
          :auto-upload="false"
          accept=".xlsx, .xls"
          :on-remove="handleRemove"
          :before-upload="beforeUploadFile"
          :on-change="fileChange"
          :on-exceed="exceedFile"
          :before-remove="beforeRemove"
          :file-list="fileList"
          drag
          :action="UploadUrl()"
          multiple
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip uploadTip">{{ uploadTip }}</div>
        </el-upload>
      </div>
      <div class="flex flextc m-t-35 ">
        <el-button class="saveBtn el-icon-circle-check m-r-30" @click="handleSave">保存</el-button>
        <el-button class="el-icon-circle-close clsoeBtn" @click="handleCloseDialog">关闭</el-button>
      </div>
    </div>
  </div>
</template>

<script>

import XLSX from 'xlsx'
import elevator from '@/entity/elevator'
import MaintenanceMan from '@/entity/MaintenanceMan'
import { importElevator } from '@/api/elevator/elevator'
import { importMaPerson } from '@/api/maintenance/maintenance'
import { showNotice } from '@/utils/toolclass'
import storage from '@/utils/storage'

export default {
  components: {},
  props: {
    uploadTip: {
      type: String,
      default: ''
    },
    fileType: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      limitNum: 1, // 上传excell时，同时允许上传的最大数
      fileList: [],
      file: {}, // excel文件列表
      files: {}, // excel文件列表
      rowIndex: 1,
      colIndex: 1,
      regCode: '',
      safeCode: ''
    }
  },
  created() {},
  methods: {
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      showNotice('error', '提示', '一次只能上传一个文件!')
    },
    // 文件状态改变时的钩子
    fileChange(file, fileList) {
      this.file = file.raw
      this.fileList.push(file.raw)
      this.files = { 0: file.raw }
      this.readExcel1(this.files)
    },
    readExcel1(files) { // 表格导入
      // var that = this
      if (files.length <= 0) { // 如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0]// 取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容
          ws.forEach(val => {
            if (val.__rowNum__ > 1) {
              this.regCode = val.__EMPTY
              this.safeCode = {
                empty: val.__EMPTY,
                empty1: val.__EMPTY_1,
                empty2: val.__EMPTY_2,
                empty3: val.__EMPTY_3,
                empty4: val.__EMPTY_4,
                empty5: val.__EMPTY_5,
                empty6: val.__EMPTY_6,
                empty7: val.__EMPTY_7,
                empty8: val.__EMPTY_8,
                empty9: val.__EMPTY_9,
                empty10: val.__EMPTY_10,
                empty11: val.__EMPTY_11,
                empty12: val.__EMPTY_12,
                empty13: val.__EMPTY_13,
                empty14: val.__EMPTY_14
              }
              if (this.fileType === 1) {
                elevator.methods.checkField(this.rowIndex, this.colIndex, this.regCode)
                this.colIndex += 1
                elevator.methods.checkField(this.rowIndex, this.colIndex, this.safeCode)
              } else {
                MaintenanceMan.methods.checkField(this.rowIndex, this.colIndex, this.regCode)
                this.colIndex += 1
                MaintenanceMan.methods.checkField(this.rowIndex, this.colIndex, this.safeCode)
              }
              this.rowIndex += 1
              this.colIndex = 1
            }
          })
          // that.peopleArr = [];//清空接收数据
          // if(that.peopleArr.length == 1 && that.peopleArr[0].roleName == "" && that.peopleArr[0].enLine == ""){
          //     that.peopleArr = [];
          // }
          // 重写数据
          try {
            console.log('')
          } catch (err) {
            console.log(err)
          }
          this.$refs.upload.value = ''
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      // const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      const size = file.size / 1024 / 1024

      // if (extension !== 'xlsx' || extension !== 'xls') {
      //   this.$message.warning('只能上传后缀是.xlsx和.xls的文件')
      // }
      if (size > 5) {
        this.$message.warning('文件大小不得超过5M')
      }
    },
    UploadUrl: function() {
      // 因为action参数是必填项，我们使用二次确认进行文件上传时，直接填上传文件的url会因为没有参数导致api报404，所以这里将action设置为一个返回为空的方法就行，避免抛错
      return ''
    },
    handleSave() {
      if (this.fileList.length === 0) {
        showNotice('error', '提示', '请上传文件!')
      } else {
        this.$emit('update', this.file)
        this.$emit('handleCloseDialog')
        this.$refs.upload.clearFiles()
        this.fileList = []
        const form = new FormData()
        form.append('importFile', this.file)
        if (this.fileType === 1) {
          importElevator(form).then(res => {
            this.$emit('error-msg', res)
            if (res.code === '000000') {
              showNotice('success', '提示', '文件上传成功!')
            } else {
              if (res.code === '111111') {
                showNotice('error', '提示', '备案未完成，无法使用本模块，请先完成备案')
              } else {
                showNotice('error', '提示', '上传失败，请重新上传!')
              }
            }
          })
        } else if (this.fileType === 0) {
          importMaPerson(form).then(res => {
            this.$emit('error-msg', res)
            if (res.code === '000000') {
              showNotice('success', '提示', '文件上传成功!')
            } else {
              if (res.code === '111111') {
                showNotice('error', '提示', '备案未完成，无法使用本模块，请先完成备案')
              } else {
                showNotice('error', '提示', '上传失败，请重新上传!')
              }
            }
          })
        }
      }
    },
    handleRemove(file, fileList) {
      const list = this.$refs.upload.uploadFiles
      const index = list.findIndex(item => {
        return item.uid === file.uid
      })
      list.splice(index, 1)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleCloseDialog() {
      this.$emit('handleRefresh')
      this.$emit('handleCloseDialog')
    }
  }
}
</script>

<style rel='stylesheet/scss' lang='scss' scoped>
.produceFactoryDialog {
  width: 100%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  min-height: 450px;
  background-color: #f5f5f5;
  border-radius: 5px;
  .uploadTip{
    color: #ff0000;
  }
  .con {
    padding-top: 16px;
  }
  .panelWrap {
    height: 100%;
    position: absolute;
    width: 100%;
  }
  .con-row {
    padding: 10px 0 0 0;
    .inputLable {
      .name {
        width: 36%;
        text-align: right;
      }
      .input {
        margin-left: 3px;
      }
    }
    .textarea {
      width: 260px !important;
      border-style: solid;
      border-width: 1px;
      border-color: var(--inputbc);
      outline: none;
      height: 70px;
      border-radius: 3px;
    }
  }
  .footerBtn {
    .defaultbtn {
      width: 75px;
      height: 32px;
    }
  }
}
.upload-demo {
    width: 60%;
    margin: 30px auto 20px auto;
}
.footerBtn{
  position: absolute;
  bottom: 20px;
  width: 100%;

}
</style>
